package com.namecard.namecardapi.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.namecard.namecardapi.entity.UserInfo;
import com.namecard.namecardapi.entity.vo.LoginVO;
import com.namecard.namecardapi.entity.vo.ResponseVO;
import com.namecard.namecardapi.service.UserInfoService;
import com.namecard.namecardapi.util.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


/**
 * @author: wjh
 */
@Api(tags = "用户登录接口")
@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {

    @Resource
    private UserInfoService userInfoService;

    @Value(value = "${twitter.consumerkey}")
    private String CONSUMER_KEY;
    @Value(value = "${twitter.consumersecret}")
    private String CONSUMER_SECRET;
    //    private  static final  String CALLBACK_URL = "https://tocys.piftware.com/login/twitterCallbackUrl";
    @Value(value = "${twitter.callbackurl}")
    private String CALLBACK_URL;

    @Value(value = "${twitter.accesstoken}")
    private String ACCESS_TOKEN;
    @Value(value = "${twitter.accesstokensecret}")
    private String ACCESS_TOKEN_SECRET;

    /**
     * 前端域名
     **/
    @Value(value = "${domain.url}")
    private String DOMAIN_URL;

    //创建推特对象
    private Twitter createTwitterInstance() {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET).setIncludeEmailEnabled(true);
        TwitterFactory tf = new TwitterFactory(cb.build());
        return tf.getInstance();
    }

    //    twitter登录 步骤1
    @ApiOperation("twitter登录")
    @GetMapping("/twitter")
    public ResponseVO<Object> twitter() {
        // 开发环境才会用到这两行代码，这个是vpn代理的端口，生产环境肯定没有vpn了，所以这里不能写死
        //测试和开发环境可以用java -DproxyHost=127.0.0.1 -DproxyPort=7890 -jar your-application.jar
//        System.setProperty("proxyPort", "7890");
//        System.setProperty("proxyHost", "127.0.0.1");
        Twitter twitter = createTwitterInstance();
        System.out.println("推特登录第一步触发了");
        try {
            System.out.println(CALLBACK_URL);
            RequestToken requestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
            String authUrl = requestToken.getAuthenticationURL();
            Map<String, String> response = new HashMap<>();
            response.put("authUrl", authUrl);
            return ResponseVO.getSuccessResponseVo(response);
        } catch (TwitterException e) {
            e.printStackTrace();
            return ResponseVO.getErrorResponseVo(Collections.emptyMap());
        }
    }

    //    twitter 步骤2  https://tocys.piftware.com/login/twitterCallbackUrl
    @GetMapping("/twitterCallbackUrl")
    public void twitterCallback(@RequestParam("oauth_token") String oauthToken, @RequestParam("oauth_verifier") String oauthVerifier, HttpServletResponse response) throws IOException {
        Twitter twitter = createTwitterInstance();
        AccessToken accessToken = null;
        System.out.println("推特登录第二步触发了");
        try {
            accessToken = twitter.getOAuthAccessToken(new RequestToken(oauthToken, ""), oauthVerifier);
            //获取访问令牌和密钥
            String token = accessToken.getToken();
            String secret = accessToken.getTokenSecret();
            //使用访问令牌和密钥创建推特对象
            Twitter twitterWithToken = createTwitterInstance();
            twitterWithToken.setOAuthAccessToken(new AccessToken(token, secret));
            //获取当前用户信息
            User user = twitterWithToken.verifyCredentials();
            //插入/或不插入数据库
            UserInfo userInfo = new UserInfo();
            userInfo.setId(user.getId());   //这里是设置推特id，你什么时候注册推特的这里的雪花id就是什么
            userInfo.setUserId("x-" + user.getScreenName()); //这里是设置推特账号，就是@符号后面的，账号在推特中也是唯一的，这里就作为userId吧
            userInfo.setUserName(user.getName());         //这里是设置推特昵称
            userInfo.setAccessToken(TokenUtil.getToken(userInfo.getUserId()));
            UserInfo userInfo_db = userInfoService.getByIdOrUserId(userInfo.getId(), userInfo.getUserId());
            if (userInfo_db == null) {
                userInfoService.save(userInfo);
            }
            userInfo.setId(null);
            ResponseVO<UserInfo> result = ResponseVO.getSuccessResponseVo(userInfo);
            result.setData(userInfo);
            String jsonData = URLEncoder.encode(JSON.toJSONString(result), "UTF-8");
//            {"code":200,"data":{"accessToken":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiJ4LUp1bk1vU2hlbGwiLCJleHAiOjE3MjM5ODUyMjN9.Hy0rojQIbtQnGLXTGGMKhLBeWB-yK8gz_muIP_2ZKo8","userId":"x-JunMoShell","userName":"君莫笑"},"info":"请求成功","status":"success"}
            System.out.println(jsonData);
            //TODO 这里重定向需要注意跳转到前端域名
            response.sendRedirect(DOMAIN_URL+"TwitterValidate?result=" + jsonData);
        } catch (TwitterException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * facebook登录，这里是由前端回调的
     *
     * @param userInfo
     * @return
     * @throws IOException
     */
    @PostMapping("/faceBookCallbackUrl")
    public ResponseVO<UserInfo> faceBookCallback(@RequestBody UserInfo userInfo) throws IOException {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getId, userInfo.getId()).or().eq(UserInfo::getUserId, "f-" + userInfo.getUserId());
        UserInfo user_db = userInfoService.getOne(queryWrapper);
        String token = TokenUtil.getToken(userInfo.getUserId());
        if (user_db == null) {
            if (userInfo.getUserId() == null || StrUtil.isEmpty(userInfo.getUserId())) {
                return ResponseVO.getErrorResponseMsg("用户信息为空");
            } else {
                userInfo.setAccessToken(token);
                userInfo.setUserId("f-" + userInfo.getUserId());
                userInfoService.save(userInfo);
            }
        }
        userInfo.setId(null);
        userInfo.setAccessToken(token);
        return ResponseVO.getSuccessResponseVo(userInfo);
    }

    @ApiOperation("验证用户信息")
    @PostMapping("/authenticate")
    public ResponseVO<Object> authenticate(@RequestBody UserInfo userInfo) {
        String userId = TokenUtil.getUserId(userInfo.getAccessToken());
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserId, userId);
        if (userInfoService.getOne(queryWrapper) != null) {
            return ResponseVO.getSuccessResponseVo(userInfo);
        }
        return ResponseVO.getErrorResponseMsg("用户不存在");
    }

    /*
      删除Facebook用户登录信息
     */
//    @ApiOperation("删除Facebook用户登录信息")
//    @GetMapping("/deleteFaceBook")
//    public Map<String,String> deleteFaceBook(@RequestParam String id) {
//        Map<String, String> map = new HashMap<>();
//        map.put("url", "https://www.facebook.com/logout.php?next=https://www.facebook.com/&access_token="+id);
//        map.put("code", "200");
//        return map;
//    }
}
